package com.easychat.websocket;

import com.easychat.dto.MessageSendDto;
import com.easychat.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

/**
 * @author 10 2024/10/20
 */
@Slf4j
@Component("messageHandler")
public class MessageHandler {
    private static final String MESSAGE_TOPIC = "message.topic";

    @Resource
    private RedissonClient redissonClient;
    @Resource
    private ChannelContextUtils channelContextUtils;

    @PostConstruct
    public void lisMessage(){
        RTopic rTopic = redissonClient.getTopic(MESSAGE_TOPIC);
        List<String> channelNames = rTopic.getChannelNames();
        rTopic.addListener(MessageSendDto.class,(MessageSendDto,sendDto)->{
                log.info("收到广播消息：{}", JsonUtils.convertObj2Json(sendDto));
                channelContextUtils.sendMessage(sendDto);

        });
    }
    public void sendMessage(MessageSendDto sendDto){
        RTopic rTopic = redissonClient.getTopic(MESSAGE_TOPIC);
        rTopic.publish(sendDto);

    }
}
